<?php

namespace App\Http\Controllers;

/**
 * api接口控制器公共类
 * 禁止再这里实现api接口
 */
class BaseController extends Controller
{

    /**
     * 接口返回方法
     * @param $code 状态码
     * @param $msg 提示信息
     * @param string $arr 需要返回给前端的数据
     * @var $code 具体状态码请根据http状态码进行是定义
     */
    public function send($code, $msg, $arr = '')
    {
        $array = [
            'code' => (string)$code,
            'msg' => trim($msg),
        ];
        if (!empty($arr)) {
            $array['data'] = $this->forString($arr);
        }

        echo json_encode($array, JSON_UNESCAPED_UNICODE);
        exit;
    }

    /**
     * 转字符串格式
     *
     */
    private function forString($arr)
    {
        if (!is_array($arr)) return (string)$arr;
        foreach ($arr as $k => $v) {
            if (is_array($v)) {
                $arr[$k] = $this->forString($v);
            } else {
                $arr[$k] = (string)$v;
            }
        }
        return $arr;
    }

    /**
     * 生成邀请码（生成8位唯一UUID）
     * @return string
     */
    protected function createInvitationCode(){
        $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $rand = $code[rand(0,25)]
            .strtoupper(dechex(date('m')))
            .date('d').substr(time(),-5)
            .substr(microtime(),2,5)
            .sprintf('%02d',rand(0,99));
        for(
            $a = md5( $rand, true ),
            $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
            $d = '',
            $f = 0;
            $f < 8;
            $g = ord( $a[ $f ] ),
            $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
            $f++
        );
        return  $d;
    }

    /**
     * 时间转换函数
     * @param $time 须为Unix时间戳，如果不是请先用strtotime()将其转换成Unix时间戳
     * @return false|string
     */
    public function tranTime($time)
    {
        $original_time = $time;
        $rtime = date("m-d H:i", $time);
        $htime = date("H:i", $time);

        $time = time() - $time;

        if ($time < 60) {
            $str = '刚刚';
        } elseif ($time < 60 * 60) {
            $min = floor($time / 60);
            $str = $min . '分钟前';
        } elseif ($time < 60 * 60 * 24) {
            $h = floor($time / (60 * 60));
            $str = $h . '小时前';
        } elseif ($time < 60 * 60 * 24 * 4) {
            $d = floor($time / (60 * 60 * 24));
            //if ($d == 1){$str = '昨天 ' . $rtime;}
            $str = $d.'天前';
        } else {
            //$str = $rtime;
            $str =  date("m-d", $original_time);
        }
        return $str;
    }



}
